<template>
  <div>
    <h1 class="my-4 text-4xl font-semibold">新建博客</h1>
    <PostForm @success="onSuccess" :is-fetching="isFetching" />
  </div>
</template>
<script setup lang="ts">
import { ApiResponse, useApiFetch } from "@/composables/useApiFetch";
import { SubmissionContext } from "vee-validate";

const { isFetching, data, post } = useApiFetch<ApiResponse>("/user/posts", {
  immediate: false,
});
const router = useRouter();
const onSuccess = async (values: any, { resetForm }: SubmissionContext) => {
  // 上传图片需要使用formData
  const formData = new FormData();
  Object.entries(values).forEach(([key, value]) => {
    if (value instanceof File) formData.append(key, value, value.name);
    else formData.append(key, value as string);
  });
  await post(formData).json().execute();
  if (data.value?.success) {
    // 重置表单
    resetForm();
    // 跳转到我的博客
    router.push({ name: "my.index" });
  }
};
</script>
